<?php if(!empty($subvo)){
    $v = $subvo;
    $subvo = '';
}
if(!empty($subsubvo)){
    $v = $subsubvo;
    $subsubvo = '';
}
?>
<div class="viewBox myBox<?php echo $v['id'];?>" <?php if($_SESSION[C('USER_AUTH_KEY')]){?> sortID="<?php echo $v['sort'];?>" modulesID="<?php echo $v['id'];?>" title="<?php echo $v['title'];?>" deleteUrl="<?php echo U('/Admin/Modules/delete',array('id'=>$v['id']));?>" settingUrl="<?php echo U('/Admin/Modules/edit',array('id'=>$v['id']));?>" isEdit="0"<?php }?>>
  <?php if(!empty($v['dataname'])){
                $v['content'] = $v['dataname'];
                
        }
         ?>
         <div class="panel panel-primary">
    <?php include(TMPL_PATH.'Home/TemplateDefault/Public-Moduletitle'.C('TMPL_TEMPLATE_SUFFIX')); ?>
<div class="panel-body">


 

<?php if($skuList){?> 

<style type="text/css">
.bh-sku-selected {color: red; background:#fff; border:1px solid #FF0033;}
input{border:1px solid #ccc; border-radius:0px; background:#fff; outline:none; border-radius:2px;}
input[disabled="disabled"]{border:1px solid #ccc; background:#eee; color:#fff;}
</style>

<link type="text/css" rel="stylesheet" href="/sku/css/shCore.css" />
<link type="text/css" rel="stylesheet" href="/sku/css/shCoreDefault.css"/>
<script type="text/javascript" src="/sku/js/json2.js"></script>
<script type="text/javascript" src="/sku/js/shCore.js"></script>
<script type="text/javascript" src="/sku/js/shBrushJScript.js"></script>



<script type="text/javascript">SyntaxHighlighter.all();</script>


<script type="text/javascript">
var startTime = new Date().getTime();
var data;
//销售属性集
$.get('{:U('Ajax/getSKU')}', {id:<?php echo $id;?>,time:startTime}, function(r){
	data = r;
	setSKU();
},'json');
//后台读取结果集

//保存最后的组合结果信息
var SKUResult = {};
//获得对象的key
function getObjKeys(obj) {
    if (obj !== Object(obj)) throw new TypeError('Invalid object');
    var keys = [];
    for (var key in obj)
        if (Object.prototype.hasOwnProperty.call(obj, key))
            keys[keys.length] = key;
    return keys;
}

//把组合的key放入结果集SKUResult
function add2SKUResult(combArrItem, sku) {
	var key = combArrItem.join(";");
    if(SKUResult[key]) {
        SKUResult[key].count += sku.count;
        SKUResult[key].prices.push(sku.price);
    } else {
        SKUResult[key] = {
            count : sku.count,
            prices : [sku.price]
        };
    }
}

//初始化得到结果集
function initSKU() {
    var i, j, skuKeys = getObjKeys(data);
    for(i = 0; i < skuKeys.length; i++) {
        var skuKey = skuKeys[i];//一条SKU信息key
        var sku = data[skuKey];	//一条SKU信息value
        var skuKeyAttrs = skuKey.split(";"); //SKU信息key属性值数组
		skuKeyAttrs.sort(function(value1, value2) {
			return parseInt(value1) - parseInt(value2);
		});

        //对每个SKU信息key属性值进行拆分组合
		var combArr = combInArray(skuKeyAttrs);
		for(j = 0; j < combArr.length; j++) {
			add2SKUResult(combArr[j], sku);
		}

        //结果集接放入SKUResult
        SKUResult[skuKeyAttrs.join(";")] = {
            count:sku.count,
            prices:[sku.price]
        }
    }
}

/**
 * 从数组中生成指定长度的组合
 * 方法: 先生成[0,1...]形式的数组, 然后根据0,1从原数组取元素，得到组合数组
 */
function combInArray(aData) {
	if(!aData || !aData.length) {
		return [];
	}

	var len = aData.length;
	var aResult = [];

	for(var n = 1; n < len; n++) {
		var aaFlags = getCombFlags(len, n);
		while(aaFlags.length) {
			var aFlag = aaFlags.shift();
			var aComb = [];
			for(var i = 0; i < len; i++) {
				aFlag[i] && aComb.push(aData[i]);
			}
			aResult.push(aComb);
		}
	}
	
	return aResult;
}


/**
 * 得到从 m 元素中取 n 元素的所有组合
 * 结果为[0,1...]形式的数组, 1表示选中，0表示不选
 */
function getCombFlags(m, n) {
	if(!n || n < 1) {
		return [];
	}

	var aResult = [];
	var aFlag = [];
	var bNext = true;
	var i, j, iCnt1;

	for (i = 0; i < m; i++) {
		aFlag[i] = i < n ? 1 : 0;
	}

	aResult.push(aFlag.concat());

	while (bNext) {
		iCnt1 = 0;
		for (i = 0; i < m - 1; i++) {
			if (aFlag[i] == 1 && aFlag[i+1] == 0) {
				for(j = 0; j < i; j++) {
					aFlag[j] = j < iCnt1 ? 1 : 0;
				}
				aFlag[i] = 0;
				aFlag[i+1] = 1;
				var aTmp = aFlag.concat();
				aResult.push(aTmp);
				if(aTmp.slice(-n).join("").indexOf('0') == -1) {
					bNext = false;
				}
				break;
			}
			aFlag[i] == 1 && iCnt1++;
		}
	}
	return aResult;
} 



//初始化用户选择事件
function setSKU() {
	initSKU();
	
	var endTime = new Date().getTime();
	$('#init_time').text('init sku time: ' + (endTime - startTime) + " ms");
	$('.sku').each(function() {
		var self = $(this);
		var attr_id = self.attr('attr_id');
		if(!SKUResult[attr_id]) {
			self.attr('disabled', 'disabled');
		}
	}).click(function() {
		var self = $(this);

		//选中自己，兄弟节点取消选中
		self.toggleClass('bh-sku-selected').siblings().removeClass('bh-sku-selected');
		
		//已经选择的节点
		var selectedObjs = $('.bh-sku-selected');

		if(selectedObjs.length) {
			//获得组合key价格
			var selectedIds = [];
			selectedObjs.each(function() {
				selectedIds.push($(this).attr('attr_id'));
			});
			selectedIds.sort(function(value1, value2) {
				return parseInt(value1) - parseInt(value2);
			});
			var len = selectedIds.length;
			var prices = SKUResult[selectedIds.join(';')].prices;
			var maxPrice = Math.max.apply(Math, prices);
			var minPrice = Math.min.apply(Math, prices);
			$('#price').text(maxPrice > minPrice ? minPrice + "-" + maxPrice : maxPrice);
			$('#stock').html(SKUResult[selectedIds.join(';')].count);

			//用已选中的节点验证待测试节点 underTestObjs
			$(".sku").not(selectedObjs).not(self).each(function() {
				var siblingsSelectedObj = $(this).siblings('.bh-sku-selected');
				var testAttrIds = [];//从选中节点中去掉选中的兄弟节点

				if(siblingsSelectedObj.length) {
					var siblingsSelectedObjId = siblingsSelectedObj.attr('attr_id');
					for(var i = 0; i < len; i++) {
						(selectedIds[i] != siblingsSelectedObjId) && testAttrIds.push(selectedIds[i]);
					}
				} else {
					testAttrIds = selectedIds.concat();
				}
				testAttrIds = testAttrIds.concat($(this).attr('attr_id'));
				testAttrIds.sort(function(value1, value2) {
					return parseInt(value1) - parseInt(value2);
				});
				if(!SKUResult[testAttrIds.join(';')]) {
					$(this).attr('disabled', 'disabled').removeClass('bh-sku-selected');
				} else {
					$(this).removeAttr('disabled');
				}
			});
		} else {
			//设置默认价格
			$('#price').text('<?php echo $price;?>');
			$('#stock').html('<?php echo $stocks;?>');
			//设置属性状态
			$('.sku').each(function() {
				SKUResult[$(this).attr('attr_id')] ? $(this).removeAttr('disabled') : $(this).attr('disabled', 'disabled').removeClass('bh-sku-selected');
			})
		}
	});
}
</script>







<?php } ?>


<div class="panel panel-default" id="viewGoodsTop<?php echo $v['id'];?>" style="position:fixed; top:0; z-index:200; width:100%; left:0; background:#fff;">

        <div class="panel panel-default">
          <h1 style="border-top:1px solid #ccc; float:left; max-width:280px; overflow:hidden; margin-top:0; padding-top:0.5em; padding-left:0.5em; padding-right:0.5em; font-size:18px;"><?php echo $title;?></h1><p class="price" style="float:left;"><strong style="color: #f00;" >¥<span id="price" style="font-size:24px; font-family:Arial;"><?php echo $price; ?></span></strong>
          
      
         </p>
         <div style="clear:both;"></div>
          <notempty name="remark">
          <p class="remark"><?php echo $remark; ?></p>
          </notempty>
           
          
          
          
         <div class="panel-footer" style="padding:0; background:#fff; border-top:none;" >
         <?php foreach($skuList as $key => $voattr){?>
         
         <p style="margin-bottom:4px;"></p>
         
          <div class="dgscp-c" style="display:table">
          
          
          <h5 class="bt" style="display:table-cell; min-width:40px;"><strong><?php echo $voattr['title'];?></strong></h5>
          
          
          
          <div style="display:table-cell;"><?php foreach($voattr['list'] as $key => $vattr){?>
          <input class="sku" type="button"  attr_id="<?php echo $vattr['id'];?>" value="<?php echo $vattr['val'];?>" style="margin:5px;"/>
          <?php }?></div>
          
          
          
          </div>
          
          <?php }?>
          
          
          
          
          
          <?php if($skuList){?>
          
          <p style="margin-bottom:10px; border-top:1px solid #CDCDCD; margin-top:5px;"></p>
<?php }else{?>
<div style="height:5px;"></div>
<?php }?>





<div class="dgscp-c" style="display:table; width:100%;">

<div style="display:table-cell; max-width:30px; vertical-align:middle;">
<div class="input-group input-group-sm">
      <span class="input-group-btn">
        <button style="margin-right:-2px;" class="btn btn-default sub_" type="button"><i class="fa fa-minus"></i></button>
      </span>
      <input id="total_" class="form-control cartNum" style="text-align:center; box-shadow:none;" goods_id="<?php echo $cartdata[$key][0];?>" goods_title="<?php echo $cartdata[$key][1];?>" goods_price="<?php echo $cartdata[$key][3];?>" goods_attr="<?php echo $cartdata[$key][4];?>" type="text" name="" value="1">
    
       
      
      <span class="input-group-btn">
        <button class="btn btn-default add_" type="button"><i class="fa fa-plus"></i></button>
      </span>
      
      
      
    </div>

</div>






<div class="share" style="display:table-cell; max-width:30px;">
<a href="javascript:void(0);" onclick="addCart();" class="btn btn-warning addCartButton" style="display:block; border-radius:0; margin-left:5px; padding:5px 0;" >加入购物车</a></div>
<div class="share" style="display:table-cell; max-width:30px;">
<a href="javascript:void(0);" onClick="addCart_quick();" class="btn btn-danger addCartButtonQuick" style="border-radius:0; padding:5px 0; margin-left:5px; display:block;" >立即购买</a> </div>




<div class="share" style="display:table-cell; max-width:20px; font-size:10px;  color:#d63432;" onClick="showshareBox();">
&nbsp;
<i class="fa fa-share-square-o"></i>
&nbsp;分享
</div>
<div class="share" style="display:table-cell; max-width:30px;">

<a href="<?php echo U('Cart/index',array('isLogin' => 1));?>"><i style="font-size:2em; position:relative; color:#080300; margin-left:-5px; padding-top:0.1em;" class="fa fa-shopping-cart">


<span style="position:absolute; display:none !important; max-width:20px; top:0px; right:-8px; border-radius:10px; line-height:16px; background:#d63432; color:#fff; padding:3px; font-size:10px; font-family:Arial; width:20px; height:20px;" id="cartNum"></span></i></a>
</div>
</div>
<p style="margin-bottom:5px; margin-top:10px;"></p>


 






          
          
           
    
    
    
          </div>
        </div>

        

      </div>    
       
<div style="clear:both;"></div>
<!-- 下方按钮 -->

<div id="successBox" style="position:fixed; left:50%; top:50%; text-align:center; padding:10px; border-radius:5px;color:#fff; background:#000000; margin-left:-60px; margin-top:-30px; width:120px; display:none; z-index:3000;">
<p style="margin-bottom:0;"><i class="fa fa-check-circle-o"></i></p>
加入成功
</div>




<!-- 下方按钮结束 -->
       
 <div style="clear:both"></div>      
       
       
       <?php if(strtolower(GROUP_NAME) != 'admin'){?>
       
       
<script>

$('.add_').click(function(e) {
	var val = $(this).parent().prev('input').eq(0).val()*1;
	$(this).parent().prev('input').eq(0).val(val + 1);
	
	
});
$('.sub_').click(function(e) {
    var val = $(this).parent().next('input').eq(0).val()*1;
	if(val > 1){
		$(this).parent().next('input').eq(0).val(val - 1);
	}
});

	function addCart(){
		var attr = new Array();
		$('.bh-sku-selected').each(function(index, element) {
            attr.push($(this).attr('attr_id'));
        });
		$.ajax({
			url:"<?php echo U('Cart/insert');?>",
			data:"cart=1&title=<?php echo $title;?>&id=<?php echo $goods_id;?>:"+attr.join(';')+"&total="+$('#total_').val()+"&price="+$('#price').html(),
			type:'POST',
			dataType:"html",
			success: function(data){
				if(data > 0){
					updateCartNum();
					var successBox = $('#successBox');
					successBox.show();
					successBox.animate({opacity:0.8},'','',function(){
						
						setTimeout(function(){successBox.hide();successBox.css({opacity:0});},500);
						
					});
					$('#gotoCart').show();
					//success('成功加入购物车');
				}else{
					error(data);
				}
			}
		});
	}
	
	function addCart_quick(){
		var attr = new Array();
		$('.bh-sku-selected').each(function(index, element) {
            attr.push($(this).attr('attr_id'));
        });
		$.ajax({
			url:"<?php echo U('Cart/insert');?>",
			data:"cart=1&title=<?php echo $title;?>&id=<?php echo $goods_id;?>:"+attr.join(';')+"&total="+$('#total_').val()+"&price="+$('#price').html(),
			type:'POST',
			dataType:"html",
			success: function(data){
				if(data > 0){
					location.href = '<?php echo U('Cart/index',array('isLogin' => 1));?>';
				}else{
					error(data);
				}
			}
		});
	}
	
	function updateCartNum(){
		$.post('<?php echo U('Cart/getCount');?>?'+new Date().getTime(), {}, function(data){
			$('#cartNum').html(data);
			
			$('#cartNum').animate({'font-size':'12px','font-weight':'bold'},'','',function(){
				$('#cartNum').animate({'font-size':'10px','font-weight':'normal'});
			});
			$('#cartNum').show(100);
		},'html');
	}
	 
	$(document).ready(function(e) {
		var boxheight = $('#viewGoodsTop<?php echo $v['id'];?>').height();
		$('<div style="height:'+(boxheight-12)+'px;"></div>').insertBefore('#viewGoodsTop<?php echo $v['id'];?>');
        updateCartNum();
		/* 库存和销量 */
		$.get('<?php echo U('Ajax/getStockAndSale');?>',{id:<?php echo $id;?>},function(data){
			$('#saleBox').html(data.sale);
			$('#stock').html(data.stock);
			$('#zannum').html(data.zan+'次');
		},'json');
    });
	
	function zan(){
		$.get('<?php echo U('Ajax/ProductZan');?>', {id:<?php echo $id;?>}, function(data){
			if(data.status == 1){
				$('#zannum').html(data.data+'次');
			}else{
				error(data.info);
			}
		},'json');
	}
</script>
<?php }?>


</div>
</div></div>













